home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
NOVA - For the NeXT Workstation
/
NOVA - For the NeXT Workstation.iso
/
Documents
/
NeXTAnswers
/
mathematica.358
< prev
next >
Wrap
Text File
|
1992-02-06
|
3KB
|
131 lines
Mathematica communication example pipes
Q: How do I communicate with Mathematica using pipes?
A: This example is self-contained.
#include <stdio.h>
int rdchnr, rdchnw, wrtchnr, wrtchnw;
char buf[80];
main()
{
int pid;
char *mmapath, *args[5];
/*
** Open pipes for Mathematica to read and write.
** The parent process writes to the pipe that Mathematica reads,
** and vice versa.
*/
if (makepipe(&rdchnr,&rdchnw)) exit();
if (makepipe(&wrtchnr,&wrtchnw)) exit();
/*
** Split off the child process.
*/
pid = fork();
if (pid == 0)
{
/*
** *************************************************
** This is the code for the child process,
** which sets up for, and then becomes, Mathematica.
** *************************************************
*/
/* close the unneeded ends of the pipes */
close(rdchnw);
close(wrtchnr);
/* set up the arguments for, and the full path name of, Mathematica */
// mmapath = "/NextApps/Mathematica.app/Kernel/math";
mmapath = "/usr/bin/math";
args[0] = mmapath;
args[1] = "-noprompt";
args[2] = "-run";
args[3] = "ResetMedium[\"stdout\", PageWidth->80];$PrePrint=FullForm";
args[4] = (char *) 0;
/* install the pipes as Mathematica's standard input and output */
if ( dup2(rdchnr,0) == -1 )
{ perror("Error establishing read channel: "); exit(); }
if ( dup2(wrtchnw,1) == -1 )
{ perror("Error establishing write channel: "); exit(); }
/* start Mathematica */
execvp(mmapath,args);
perror("Error attempting to run Mathematica: ");
}
else
{
/*
** ****************************************
** This is the code for the parent process.
** ****************************************
*/
printf("hi there i got here\n");
/* close the unneeded ends of the pipes */
close(rdchnr);
close(wrtchnw);
/* absorb initialization messages harmlessly */
fetchresult();
givecmd("Expand[(1+x+y)^5]\n");
fetchresult();
givecmd("N[Pi,200]\n");
fetchresult();
/* tell Mathematica to shut down */
givecmd("Quit[]\\n");
}
}
int makepipe(rd,wrt)
int *rd,*wrt;
{
int piperesult, fildes[2];
piperesult = pipe(fildes);
if (piperesult) perror("Pipe creation failed:");
*rd = fildes[0];
*wrt = fildes[1];
return(piperesult);
}
givecmd(cmd)
char *cmd;
{
strcpy(buf,cmd);
write(rdchnw,buf,strlen(buf));
}
fetchresult()
{
int count, i, ch;
/*
** Read buffer after buffer of output from Mathematica,
** until a NEWLINE is seen. Because Mathematica is printing
** everything in FullForm, all output is linear, and because
** PageWidth was set to Infinity, no line breaking happens, so
** a NEWLINE means the end of a complete output expression.
*/
do {
count = read(wrtchnr,buf,80);
for ( i=0 ; i<count ; printf("%c", ch = buf[i++]) ) ;
} while (ch != '\n');
}
QA358
Valid for 1.0
Not checked yet for 2.0